#!/usr/bin/env python
import os
import urllib.request
import re
import subprocess
from pathlib import Path
from bs4 import BeautifulSoup
url = 'https://s3.eu-central-1.amazonaws.com/dasmalwerk/'
Path("compressed_malware_samples").mkdir(parents=True, exist_ok=True)
dasmalwerk = urllib.request.urlopen(urllib.request.Request(
        url, 
        data=None, 
        headers={
            'User-Agent': 'Packt'
        }
    )
).read().decode('utf-8')
soup = BeautifulSoup(dasmalwerk, 'lxml')
malware_samples = soup.findAll('key')
for sample in malware_samples:
    if(not sample.string.endswith('.zip')):
        continue
    sample_url="{0}{1}".format(url, sample.string)
    print("[*] Downloading sample: {0}".format(sample_url))
    try:
        sample_filename = 'compressed_malware_samples{0}{1}'.format(os.sep, sample.string.split('/')[-1])
        with urllib.request.urlopen(sample_url) as d, open(sample_filename, "wb") as opfile:
            data = d.read()
            opfile.write(data)
            print("    [-] Downloaded.")
        subprocess.call(['C:\\Program Files\\7-Zip\\7z.exe', 'e', sample_filename, '*', '-odecompressed_malware_samples', '-pinfected', '-y', '-r'], stdout=subprocess.DEVNULL)
        print("    [-] Uncompressed.")
    except:
        print("    [-] Error :-(")